<template>
    <!-- 对话框表单 -->
    <el-dialog
        custom-class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="baTable.form.operate == 'attr'"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px); margin: auto;'"
            >
                <el-card class="box-card">
                    <el-form :inline="true" class="demo-form-inline" v-for="(item, index) in attr" v-bind:key="index">
                        <el-form-item label="属性">
                            <el-input placeholder="属性" v-model="attr[index].name"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="danger" @click="rmAttr(index)">删除属性</el-button>
                        </el-form-item>
                        <br />
                        <el-form-item>
                            <el-tag
                                style="margin: 10px 10px 0 0"
                                v-for="tag in attr[index].attr"
                                closable
                                :key="tag"
                                @close="handleClose(tag, index)"
                                >{{ tag }}</el-tag
                            >
                            <el-input
                                v-if="attr[index].inputVisible"
                                v-model="inputValue"
                                class="ml-1 w-20 add-tag"
                                size="small"
                                @keyup.enter="handleInputConfirm(index)"
                                @blur="handleInputConfirm(index)"
                            />
                            <el-button v-else class="button-new-tag ml-1 add-tag-btn" size="small" @click="showInput(index)">+ 新增</el-button>
                        </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="addAttr">添加属性</el-button>
                    <el-button type="success" v-if="attr.length > 0" @click="general">生成规格</el-button>
                </el-card>
                <el-table :data="tableData" style="width: 100%; margin-top: 10px">
                    <el-table-column v-for="name in attrHeader" :prop="name" :key="name" :label="name" />
                    <el-table-column prop="price" label="价格" v-if="attrHeader.length > 0">
                        <template #default="scope">
                            <el-input type="number" v-model="scope.row.price" placeholder="价格" clearable :min="0" :step="1" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="stock" label="库存" v-if="attrHeader.length > 0">
                        <template #default="scope">
                            <el-input type="number" v-model="scope.row.stock" placeholder="库存" clearable :min="0" :step="1" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="image" label="图片" v-if="attrHeader.length > 0">
                        <template #default="scope">
                            <el-upload
                                class="avatar-uploader"
                                :action="url"
                                :headers="headers"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="
                                    (file) => {
                                        beforeAvatarUpload(file, scope)
                                    }
                                "
                            >
                                <img v-if="scope.row.image" :src="scope.row.image" class="avatar" width="50" height="50" />
                                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                            </el-upload>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="saveData() && baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, inject, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { ElForm, UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import calcDescartes from '/@/utils/calcDescartes.js'
import baTableClass from '/@/utils/baTable'
import { Plus } from '@element-plus/icons-vue'
import { getUrl } from '/@/utils/axios'
import { getAdminToken } from '/@/utils/common'

const formRef = ref<InstanceType<typeof ElForm>>()
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()
let attr: any = ref([])
const inputValue = ref('')
let attrHeader: any = ref([])
let tableData: any = ref([])
let url = getUrl() + '/index.php/admin/ajax/upload'
let headers = {
    batoken: getAdminToken(),
}
let rowIndex: number = 0

// attr.value.push({ inputVisible: false, attr: ['红色', '黑色'], name: '颜色' })
// attr.value.push({ inputVisible: false, attr: ['大', '中', '小'], name: '尺寸' })
const test = () => {
    console.log(123)
}

watch(
    () => baTable.form.loading,
    (newVal) => {
        if (!newVal) {
            attr.value.splice(0, attr.value.length)
            attrHeader.value.splice(0, attrHeader.value.length)
            tableData.value.splice(0, tableData.value.length)
            for (let i in baTable.form.items!.attr) {
                attr.value.push(baTable.form.items!.attr[i])
                attrHeader.value.push(baTable.form.items!.attr[i].name)
            }
            for (let i in baTable.form.items!.attrValue) {
                tableData.value.push(baTable.form.items!.attrValue[i])
            }
        }
    }
)
const addAttr = () => {
    attr.value.push({ inputVisible: false, attr: [] })
}

const showInput = (index: number) => {
    attr.value[index].inputVisible = true
}

const handleClose = (tag: string, index: number) => {
    attr.value[index].attr.splice(attr.value[index].attr.indexOf(tag), 1)
}

const handleInputConfirm = (index: number) => {
    if (inputValue.value) {
        attr.value[index].attr.push(inputValue.value)
    }
    inputValue.value = ''
    attr.value[index].inputVisible = false
}

const rmAttr = (index: number) => {
    attr.value.splice(index, 1)
    general()
}

const general = () => {
    attrHeader.value.splice(0, attrHeader.value.length)
    tableData.value.splice(0, tableData.value.length)
    let generalData = []
    let name = []
    for (let i in attr.value) {
        name.push(attr.value[i].name)
        generalData.push(attr.value[i].attr)
    }

    for (let i in name) {
        attrHeader.value.push(name[i])
    }

    let attrList = calcDescartes.general(generalData)
    for (let i in attrList) {
        let row = {
            image: '',
            stock: '',
            price: '',
            key: '',
        }
        if (typeof attrList[i] == 'string') {
            row[attrHeader.value[0]] = attrList[i]
            console.log(attrList[i])
            row.key = attrList[i]
            tableData.value.push(row)
        } else {
            let key: any = []
            for (let n in attrList[i]) {
                row[attrHeader.value[n]] = attrList[i][n]
                key.push(attrList[i][n])
            }
            row.key = key.join(',')
            for (let x in baTable.form.items!.attrValue) {
                if (baTable.form.items!.attrValue[x].key == row.key) {
                    row.price = baTable.form.items!.attrValue[x].price
                    row.stock = baTable.form.items!.attrValue[x].stock
                    row.image = baTable.form.items!.attrValue[x].image
                    break
                }
            }
            tableData.value.push(row)
        }
    }
    console.log(tableData)
}

const saveData = () => {
    baTable.form.items! = {
        id: baTable.form.items!.id,
        attr: attr.value,
        attrValue: tableData.value,
    }
    console.log(baTable.form.items)
    return true
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    tableData.value[rowIndex].image = response.data.file.full_url
}

const beforeAvatarUpload = (rawFile: any, row: any) => {
    rowIndex = row.$index
    return true
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    }
    return true
}
</script>

<style scoped lang="scss">
.add-tag {
    display: inline-block;
    width: 59px;
}
.add-tag,
.add-tag-btn {
    margin-top: 10px;
}
</style>
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}
</style>